package com.briup.gateway.config;

import cn.hutool.core.collection.CollUtil;
import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
import com.briup.common.utils.JsonWebTokenUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {


    private final AuthProperties authProperties;


    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("request.getPath() = " + request.getPath());
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        if (antPathMatcher.match(request.getPath().toString(), "/auths") && request.getMethod() == HttpMethod.POST) {
            return chain.filter(exchange);
        }

        // 3.获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        if (!CollUtil.isEmpty(headers)) {
            token = headers.get(0);
        }
        // 4.校验并解析token
        //token存在
        try {
            Claims jwt = JsonWebTokenUtils.parseJWT(token);
            String userId = jwt.getSubject();
            System.out.println("userId = " + userId);
            ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userId)).build();
            // 6.放行
            return chain.filter(ex);
        } catch (SystemException e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
